﻿using log4net;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Npgsql;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.PlaceOrderModels.Base;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Extensions;
using PlaceOrder_Shared.Helpers;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Daily;
using PlaceOrder_Shared.Models.HengSheng;
using PlaceOrder_Shared.Models.KChartRelated;
using PlaceOrder_Shared.Models.Trade;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection.Emit;
using System.Reflection.Metadata;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using System.Net;
using Microsoft.EntityFrameworkCore.Storage;
using IDatabase = PlaceOrder_Core.Services.Interfaces.IDatabase;
using UserTrade = PlaceOrder_Shared.Models.Common.UserTrade;

namespace PlaceOrder_Core.Services.Instances
{
    public class DailyData : IDailyData
    {
        readonly NpgsqlConnection connection;
        private readonly IDatabase _database;
        private readonly object _ocker = new object();
        private readonly ILog _log;
        public static  List<DateTime> Holidays1;
        public static string ChannelId = string.Empty;
        #region 静态变量
        public static decimal DefaultPVBP; //默认基点值
        public static string NewClientVersion; //最新版本

        public static Dictionary<int, string> brokerChannelDict = new Dictionary<int, string>();
        public static Dictionary<string, string> channelNameDict = new Dictionary<string, string>();
        public static List<ChatReceiver> chatReceivers = new List<ChatReceiver>();
        #endregion

        public static  List<Channel> channelList;
        public DailyData()
        {
            connection = new NpgsqlConnection("Host=postgres-10f8ccb3cbae.volces.com;Database=idbhost;Username=qtdev;Password=ngXFO3cl;Persist Security Info=True;Include Error Detail=true;Maximum Pool Size=800;MinPoolSize=200;CommandTimeout=300;Tcp Keepalive=true;Tcp Keepalive Interval=120;Tcp Keepalive Time=120;");


            //_database = database;

           
            //this.GetVersionId();
            //Task.Run(() =>
            //{
            //    GetChatReceivers();

            //    InitDic();

            //});


            AppLog.WriteInfo("进入dailydata构造函数");
            //if (DefaultPVBP == 0)
            //{
            //    DefaultPVBP = GetLastTopTrade();
            //}
        }

        private void InitDic()
        {
            chatReceivers = GetChatReceivers();
            channelList = GetAllChannels();
            if(channelList==null)
            {
                return;
            }
            foreach (var item in channelList)
            {
                channelNameDict[item.Id] = item.QtName ?? "未知";
            }
            // Populate the dictionary
            foreach (var item in chatReceivers)
            {
                brokerChannelDict[(int)item.Brokerid] = item.ChannelId.ToString();
            }
        }

        private List<Channel> GetAllChannels()
        {
            try
            {
                using (var db = _database.GetReaderContext()) // 获取写入连接
                {
                    if(db.Channels!=null&&db.Channels.Count()>0)
                    {
                        
                        return db.Channels.ToList();
                    }


                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetLastTopTrade" + ex.StackTrace);
                return null;
            }
            finally
            {

            }
            return null;
        }

        public DailyData(Database database)
        {
            connection = new NpgsqlConnection("Host=postgres-10f8ccb3cbae.volces.com;Database=idbhost;Username=qtdev;Password=ngXFO3cl;Persist Security Info=True;Include Error Detail=true;Maximum Pool Size=800;MinPoolSize=200;CommandTimeout=300;Tcp Keepalive=true;Tcp Keepalive Interval=120;Tcp Keepalive Time=120;");


            _database = database;
            //0831
            //if (DefaultPVBP == 0)
            //{
            //    DefaultPVBP = GetLastTopTrade();
            //}
        }

        private decimal GetLastTopTrade()
        {
            try
            {
                using (var db = _database.GetReaderContext()) // 获取写入连接
                {

                    string tscode1 = "";
                    DateOnly today = DateOnly.FromDateTime(DateTime.Today); // 将 DateTime 转换为 DateOnly，只保留日期部分
                    var latestTradeRecord = db.TradekchartId9s
                          .Where(t => t.Tradedate < today)
                          .GroupBy(t => new { t.Tscode, t.Volume, t.Tradedate })
                          .OrderByDescending(t => t.Key.Tradedate)
                          .ThenByDescending(t => t.Key.Volume)
                          .Select(t => new { TsCode = t.Key.Tscode, Volume = t.Key.Volume })
                          .FirstOrDefault();


                    if (latestTradeRecord != null)
                    {
                        tscode1 = latestTradeRecord.TsCode;
                        var ts = db.Tsinfos.SingleOrDefault(x => x.Tscode == tscode1);
                        if (ts != null)
                        {
                            return (decimal)ts.Basicvalue;
                        }
                        else
                        {
                            return 1;
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetLastTopTrade" + ex.StackTrace);
                return 1;
            }
            finally
            {

            }
            return 1;
        }

        public void AddCheckList(CheckListModel cl)
        {

        }

        public bool AddShilianPriceDiff(int ShiLianPriceDiffID, List<KChart> charts)
        {
            return false;
        }

        public void BondHelperSysLog(int UserID, string Action, long TargetID)
        {
            return;
            //string sql = "INSERT INTO user_trade_bondhelper_log (\"userid\", \"create_time\", \"action\", \"target_order_id\",\"login_ip\") VALUES (@UserID, @CreateTime, @Action, @TargetID, @LoginIP)";

            try
            {
                using (var db = _database.GetWriterContext()) // 获取写入连接
                {
                    // 创建一个新的 UserTradeBondhelperLog 对象，并设置属性值
                    var logEntry = new UserTradeBondhelperLog
                    {
                        Userid = UserID,
                        CreateTime = DateTime.Now,
                        Action = Action,
                        TargetOrderId = (int)TargetID,
                        LoginIp = UserHelper.LoginIP
                    };

                    // 将新创建的对象添加到上下文中
                    db.UserTradeBondhelperLogs.Add(logEntry);

                    // 保存更改到数据库
                    db.SaveChanges();
                    //using (var cmd = connection.CreateCommand())
                    //{
                    //    cmd.CommandText = sql;
                    //    cmd.ExecuteNonQuery();
                    //}
                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "BondHelperSysLog" + ex.StackTrace);
            }
            finally
            {
                _database.CloseWriter();
            }

        }

        public decimal CalcCFactor(TSInfoRow ts, string CTDName)
        {
            return 0;
        }

        public void DeletePriceDiffMinuteKchartByDate2(string name, DateOnly dtTrade, bool NoForward)
        {

        }

        public void DeletePriceDiffTradeDataByDate(PriceDiff p, DateOnly dtStart)
        {

        }

        public void DeleteTradeDataByDate(string TsCode, DateOnly dtStart, bool NoForward)
        {

        }

        public List<TSInfoRow> GetAllTSInfo()
        {
            return null;
        }

        /// <summary>
        /// 拿到所有交易员信息
        /// </summary>
        /// <returns></returns>
        public List<TradeSimUser> GetAllUsers()
        {
            List<TradeSimUser> tradeusers = new List<TradeSimUser>();
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return tradeusers;
                    }
                    List<UserInfo> AllUsers = UserHelper.GetAllUser(out string s,0);
                    var sys11 = db.SysLogininfors.ToList();
                    foreach (var user in AllUsers)
                    {
                        TradeSimUser t = new TradeSimUser() { UserName = user.userName, UserID = user.userId, NickName = user.nickName, Status = 0 };

                        // 使用 LINQ 查询来获取最大登录时间和经纪人列表
                        var loginInfo = db.SysLogininfors
                            .Join(db.ChatPrivilegeLists,
                                  login => login.UserName,
                                  privilege => privilege.UserName,
                                  (login, privilege) => new { login, privilege })
                            .Where(joined => joined.login.UserName == t.UserName)
                            .GroupBy(joined => joined.privilege.BrokerList)
                            .Select(group => new { MaxLoginTime = group.Max(item => item.login.LoginTime), BrokerList = group.Key })
                            .FirstOrDefault();

                        if (loginInfo != null)
                        {
                            t.LoginTime = loginInfo.MaxLoginTime ?? DateTime.MinValue;
                            List<string> brokers = loginInfo.BrokerList.Split(',').ToList();
                            foreach (var str in brokers)
                            {
                                t.BrokerList.Add(int.Parse(str));
                            }
                        }

                        tradeusers.Add(t);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message + "DailyData" + "GetAllUsers" + ex.StackTrace);
            }
            return tradeusers;
        }


        public PlaceOrder_Shared.Models.Daily.DailyData GetDailyData(string TsCode, TradeHistoryRow thr = null)
        {
            return null;
        }

        public DateOnly GetFirstCrawlDate(string TsCode)
        {
            return DateOnly.FromDateTime(DateTime.Now);
        }

        public void GetFirstMinuteKChartTime(string TsCode, ref DateTime dtTrade, bool NoForward)
        {

        }

        public void GetFirstMinuteKChartTimeInPriceDiff(string name, ref DateTime dtTrade, bool NoForward)
        {

        }

        public void GetFirstMinuteKChartTimeInPriceDiff2(string name, ref DateTime dtTrade, bool NoForward)
        {

        }

        public DateOnly GetLastCBD10Y(Cbd10YPriceDiffList p)
        {
            return DateOnly.FromDateTime(DateTime.Now);
        }

        public void GetNetPrice(decimal yield, TSInfoRow ts, string dTrade, out decimal FullPrice, out decimal NetPrice)
        {
            NetPrice = 0;
            FullPrice = 1;
        }

        public DailyDataPriceDiff GetPriceDiff(PriceDiff p)
        {
            return null;
        }

        public List<UserTrade> GetUserTrades(int userId = 0)
        {
            // 创建并启动 Stopwatch 实例
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            List<UserTrade> trades = new List<UserTrade>();

            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return trades;
                    }

                    IQueryable<UserTrade> query = null;
                    var chatReceivers = GetChatReceivers();

                    var receiverId = db.UserTradeBondhelpers
                        .Where(trade => trade.Userid == userId)
                        .OrderByDescending(trade => trade.Time)
                        .Select(trade => (int?)trade.ReceiverId)
                        .FirstOrDefault();
                    var target = receiverId != null ? chatReceivers.FirstOrDefault(x => x.Id == receiverId)?.Target : "未知";

                    if (userId == 0)
                    {
                        query = from trade in db.UserTradeBondhelpers
                                join user in db.SysUsers
                                on trade.Userid equals user.UserId
                                orderby trade.Time descending
                                select new UserTrade
                                {
                                    TsCode = trade.Tscode,
                                    UserTradeID = trade.UserTradeId,
                                    Price = trade.Price,
                                    Volume = trade.Volume,
                                    Broker = trade.Broker,
                                    ChatID = trade.Chatid,
                                    UserID = trade.Userid,
                                    Status = trade.Status,
                                    DealType = trade.Dealtype,
                                    DeliveryDate = trade.Deliverydate,
                                    Time = trade.Time,
                                    ReceiverId = (int)trade.ReceiverId,
                                    Id = trade.Id,
                                    Target = trade.Broker + "-" + (target ?? "未知"),

                                    Command = trade.Command,
                                    UserName = user.NickName,
                                    OrderType = (UserTrade.UserTradeOrderTypeEnum)trade.OrderType,
                                    Guid = (Guid)trade.Guid,
                                    DailyID = (int)trade.DailyId,
                                    OnHoldVolume = trade.RestVolume.ToInt32OrDefault(0),
                                    BrokerID = (int)trade.BrokerId,
                                    StatusText = TradeStatusHelper.GetStatusText(trade.Status),
                                };
                    }
                    else
                    {
                        userId = UserHelper.UserID;
                        query = from trade in db.UserTradeBondhelpers
                                join user in db.SysUsers
                                on trade.Userid equals user.UserId
                                where trade.Userid == userId
                                orderby trade.Time descending
                                select new UserTrade
                                {
                                    TsCode = trade.Tscode,
                                    UserTradeID = trade.UserTradeId,
                                    Price = trade.Price,
                                    Volume = trade.Volume,
                                    Broker = trade.Broker,
                                    ChatID = trade.Chatid,
                                    UserID = trade.Userid,
                                    Status = trade.Status,
                                    DealType = trade.Dealtype,
                                    DeliveryDate = trade.Deliverydate,
                                    Time = trade.Time,
                                    ReceiverId = (int)trade.ReceiverId,
                                    Id = trade.Id,
                                    Target = trade.Broker + "-" + (target ?? "未知"),

                                    Command = trade.Command,
                                    UserName = user.NickName,
                                    OrderType = (UserTrade.UserTradeOrderTypeEnum)trade.OrderType,
                                    Guid = (Guid)trade.Guid,
                                    DailyID = (int)trade.DailyId,
                                    OnHoldVolume = trade.RestVolume.ToInt32OrDefault(0),
                                    BrokerID = (int)trade.BrokerId,
                                    StatusText = TradeStatusHelper.GetStatusText(trade.Status),
                                };
                    }

                    List<UserTrade> tradesList = new List<UserTrade>();

                    Parallel.ForEach(query, result =>
                    {
                        int brokerId = (int)result.BrokerID;

                        if (brokerChannelDict.TryGetValue(brokerId, out var channelId))
                        {
                            var qtName = channelNameDict.TryGetValue(channelId, out var name) ? name : "Unknown";
                            result.BrokerDetailInfo = $"{result.Broker}-{qtName}-{result.ChatID}";
                        }
                        else
                        {
                            result.BrokerDetailInfo = $"{result.Broker}-Unknown-{result.ChatID}";
                        }

                        lock (tradesList)
                        {
                            tradesList.Add(result);
                        }
                    });

                    tradesList = tradesList
                        .OrderBy(p => p.Status)
                        .ThenByDescending(o => o.Time)
                        .ToList();

                    return tradesList;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetUserTrades" + ex.StackTrace);
            }
            finally
            {
                // 停止 Stopwatch 并记录耗时
                stopwatch.Stop();
                AppLog.WriteWarn($"GetUserTrades 方法耗时: {stopwatch.ElapsedMilliseconds} 毫秒");
            }

            return trades;
        }
        private string GetQtName(int channelId, List<Channel> channelList)
        {
            var channel = channelList.FirstOrDefault(cl => cl.Id == channelId.ToString());
            return channel != null ? channel.QtName : ""; // 返回 QtName 或默认空字符串
        }

        private string GetStatusText(int status)
        {
            switch (status)
            {
                case 0:
                case 1:
                    return "已接收";
                case 3:
                    return "已成交";
                case 4:
                    return "部分成交";
                case 5:
                    return "已撤单";
                case 6:
                    return "部分撤单";
                case 9:
                    return "待确认";
                case 13:
                    return "已作废";
                default:
                    return "已完成";
            }
        }

        public List<KChart> GetWindKChart(TSInfoRow ts, DateOnly qbdate)
        {
            return null;
        }

        public void RepairMinuteKchartVolume(TSInfoRow ts)
        {

        }

        public bool UpdateKchart(string TsCode, KChart k)
        {
            return false;
        }

        public void UpdatePriceDiffKChart2(TSInfoRow ts, PriceDiff p, List<KChart> charts)
        {

        }

        public void UpdateValuation(int iFlag, int Length, List<KChart> charts)
        {

        }


        /// <summary>
        /// 获取所有聊天接收者
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List<ChatReceiver> GetChatReceivers(int UserID = 0)
        {

            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return new List<ChatReceiver>(); // 返回一个空列表
                    }

                    List<ChatReceiver> receivers = null;
                    if (UserID == 0)
                    {
                        // 在此处进行查询并赋值给 receivers
                        var temp = db.ChatReceivers.ToList();
                        receivers = db.ChatReceivers
                            .Where(receiver => receiver.Deleted == false)
                            .OrderBy(receiver => receiver.Id)
                            .Select(receiver => new ChatReceiver // 假设 Receiver 是 ChatReceiver 的实体类
                            {
                                Id = receiver.Id,
                                Target = receiver.Target,
                                Company = receiver.Company,
                                Tscode = receiver.Tscode,
                                ChatId = receiver.ChatId,
                                GroupName = receiver.GroupName,
                                Brokerid = receiver.Brokerid,
                                ChannelId = receiver.ChannelId
                            })
                            .ToList();

                    
                    }
                    else
                    {
                        var brokerList = db.ChatPrivilegeLists
                    .Where(item => item.UserId == UserID)
                    .Select(item => item.BrokerList)
                    .FirstOrDefault();
                        if (brokerList != "")
                        {
                            receivers = db.ChatReceivers
    .Where(o => !o.Deleted.GetValueOrDefault() && brokerList.Contains(o.Id.ToString()))
    .OrderBy(u => u.Id)
    .Select(p => new ChatReceiver // 假设 ChatReceiver 是你的实体类
    {
        Id = p.Id,
        Target = p.Target,
        Company = p.Company,
        Tscode = p.Tscode,
        ChatId = p.ChatId,
        GroupName = p.GroupName,
        Brokerid = p.Brokerid,
        ChannelId=p.ChannelId
    })
    .ToList();



                        }
                    }


                    return receivers ?? new List<ChatReceiver>(); // 处理空引用情况
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetChatReceivers" + ex.StackTrace);
            }
            return new List<ChatReceiver>(); // 处理空引用情况
        }

        public async Task<List<ChatReceiver>> GetChatReceiversAsync(int UserID = 0)
        {
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return new List<ChatReceiver>(); // 返回一个空列表
                    }

                    List<ChatReceiver> receivers = null;
                    if (UserID == 0)
                    {
                        // 异步查询并赋值给 receivers
                        receivers = await db.ChatReceivers
                            .Where(receiver => receiver.Deleted == false)
                            .OrderBy(receiver => receiver.Id)
                            .Select(receiver => new ChatReceiver
                            {
                                Id = receiver.Id,
                                Target = receiver.Target,
                                Company = receiver.Company,
                                Tscode = receiver.Tscode,
                                ChatId = receiver.ChatId,
                                GroupName = receiver.GroupName,
                                Brokerid = receiver.Brokerid
                            })
                            .ToListAsync();
                    }
                    else
                    {
                        var brokerList = await db.ChatPrivilegeLists
                            .Where(item => item.UserId == UserID)
                            .Select(item => item.BrokerList)
                            .FirstOrDefaultAsync();

                        if (!string.IsNullOrEmpty(brokerList))
                        {
                            // 异步查询并赋值给 receivers
                            receivers = await db.ChatReceivers
                                .Where(o => !o.Deleted.GetValueOrDefault() && brokerList.Contains(o.Id.ToString()))
                                .OrderBy(u => u.Id)
                                .Select(p => new ChatReceiver
                                {
                                    Id = p.Id,
                                    Target = p.Target,
                                    Company = p.Company,
                                    Tscode = p.Tscode,
                                    ChatId = p.ChatId,
                                    GroupName = p.GroupName,
                                    Brokerid = p.Brokerid
                                })
                                .ToListAsync();
                        }
                    }

                    return receivers ?? new List<ChatReceiver>(); // 处理空引用情况
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetChatReceivers" + ex.StackTrace);
                return new List<ChatReceiver>(); // 处理异常情况并返回空列表
            }
        }

        #region 客户端接口实现

        public string GetVersionId()
        {
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return null; // 返回一个空列表
                    }

                    NewClientVersion = db.ClientVersions.ToList()[0].VersionId;
                    return db.ClientVersions.ToList()[0].VersionId;
                   
                }
            }
            catch(Exception ex)
            {
                return null;
            }
        }


        /// <summary>
        /// 根据用户id获取所有审核消息
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<ReviewMessage> GetAllReviewMessages(int userId)
        {
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return new List<ReviewMessage>(); // 返回一个空列表
                    }

                    List<ReviewMessage> reviewMessages = null;
                    if (userId == 0)
                    {
                        reviewMessages = db.ReviewMessages.ToList();
                        // 查询所有 ReviewMessage，并包含关联的 UserTrade
                        var userTradeBondhelpers = db.UserTradeBondhelpers.ToList();

                        foreach (var message in reviewMessages)
                        {
                            // 找到对应的 UserTradeBondhelper
                            var correspondingBondhelper = userTradeBondhelpers.FirstOrDefault(ut => ut.UserTradeId == message.UserTradeId);

                            // 如果找到对应的 UserTradeBondhelper，则赋值给 ReviewMessage 的 UserTradeBondhelper 属性
                            if (correspondingBondhelper != null)
                            {
                                message.UserTradeBondhelper = correspondingBondhelper;
                            }
                            else
                            {
                                // 处理未找到对应的 UserTradeBondhelper 的情况，可以根据需求进行逻辑处理
                            }
                        }
                        return reviewMessages;
                    }
                    else
                    {
                        // 根据 userId 查询 ReviewMessage，并包含关联的 UserTrade
                        reviewMessages = db.ReviewMessages
                                           .Include(rm => rm.UserTradeBondhelper)
                                           .Where(rm => rm.UserId == userId)
                                           .ToList();
                    }

                    return reviewMessages ?? new List<ReviewMessage>(); // 处理空引用情况
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetAllReviewMessages" + ex.StackTrace);
                return new List<ReviewMessage>(); // 处理异常情况并返回空列表
            }
        }




        /// <summary>
        /// 根据中介id获取所有消息
        /// </summary>
        /// <param name="brokerId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<ChatMessage> GetAllMessageDataByBrokerId(int brokerId, int userId = 0)
        {
            List<ChatMessage> messageList = new List<ChatMessage>();
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return messageList;
                    }
                    // Query to fetch trade data
                    //默认当前用户 0代表所有消息 只根据中介来区分
                    if(userId==0)
                    {
                        return db.ChatMessages.Where(o => o.BrokerId == brokerId).OrderBy(item=>item.CreateTime).ToList();
                    }else
                    {
                        return db.ChatMessages.Where(o => o.BrokerId == brokerId && o.ChatId == userId).OrderBy(item => item.CreateTime).Take(200).ToList();
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetAllMessageDataByBrokerId" + ex.StackTrace);
            }
            return messageList;
        }
        /// <summary>
        /// 计算回撤量时更新
        /// </summary>
        /// <param name="user"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void UpdateQuanyiSimUserDrawDown(TradeSimUser user)
        {
            try
            {
                using (var db = _database.GetWriterContext()) // 获取写入连接
                {

                    var userToUpdate = db.TradeSimulationUsers.FirstOrDefault(u => u.UserId == user.UserID);

                    if (userToUpdate != null)
                    {
                        userToUpdate.DailyDrawDown = user.DailyDrawDown;
                        userToUpdate.DrawDownDate = DateOnly.FromDateTime(DateTime.Now.Date); // 使用日期的 Date 部分

                        db.SaveChanges(); // 保存更改到数据库
                    }

                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "UpdateQuanyiSimUserDrawDown" + ex.StackTrace);
            }
            finally
            {
                _database.CloseWriter();
            }
        }


        public List<QuanyiClientTradeClass> GetQuanyiSimulationTrades()
        {
            List<QuanyiClientTradeClass> tradeClasses = new List<QuanyiClientTradeClass>();
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return tradeClasses;
                    }
                    // Query to fetch trade data
                    var query = from ts in db.TradeSimulations
                                where (ts.UserId == UserHelper.UserID &&
                                       (DateTime.Now.Date - ts.Orderdate.Date).Days <= 1 || ts.Onholdvolume > 0)
                                orderby ts.Orderdate descending
                                select new QuanyiClientTradeClass
                                {
                                    TsCode = ts.Tscode,
                                    UserID = UserHelper.UserID,
                                    OrderDate = ts.Orderdate,
                                    TradeDate = ts.Tradedate ?? DateTime.MinValue,
                                    Price = ts.Price,
                                    Volume = ts.Volume,
                                    DealType = ts.Dealtype,
                                    TradeResult = ts.Result,
                                    ID = ts.Id,
                                    Status = (QuanyiClientTradeClass.TradeStatus)ts.Status,
                                    OpponentID = ts.OpponentId,
                                    Profit = (decimal)ts.Profit,
                                    OnHoldVolume = (int)ts.Onholdvolume,
                                    NetPrice = (decimal)ts.Netprice,
                                    PVBP = (decimal)ts.Pvbp,
                                    OrderType = (QuanyiClientTradeClass.OrderTypeEnum)ts.Ordertype,
                                    Guid = (Guid)ts.Guid,
                                    BalanceOrder = (int)ts.BalanceOrder
                                };
                    tradeClasses = query.ToList();
                    return tradeClasses;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetQuanyiSimulationTrades" + ex.StackTrace);
            }
            return tradeClasses;
        }

        public TradeSimUser GetTradeSimSingleUser(int UserID)
        {
            TradeSimUser tradeuser = new TradeSimUser();
            tradeuser.Activated = false;
            string sql = $"select a.id,user_id,max_profit,max_loss,b.allowed_total_loss,b.volume,allowed_daily_loss,activated,user_status,disable_start_date,daily_draw_down,a.user_privilege,draw_down_date from trade_simulation_users as a inner join trade_simulation_config as b on a.user_privilege = b.id where user_id = {UserID}";
            try
            {
                using (var cmd = new NpgsqlCommand(sql, connection))
                {
                    connection.Open(); // 打开连接
                    using (var reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            tradeuser.id = reader.GetInt32(0);
                            tradeuser.UserID = reader.GetInt32(1);
                            tradeuser.MaxProfit = reader.GetDecimal(2);
                            tradeuser.MaxLoss = reader.GetDecimal(3);
                            tradeuser.AllowedTotalLoss = reader.GetDecimal(4);
                            tradeuser.TotalAllowedSingleOpen = reader.GetInt32(5);
                            tradeuser.TotalAllowedMaxOpen = tradeuser.TotalAllowedSingleOpen;
                            tradeuser.AllowedDailyLoss = reader.GetDecimal(6);
                            tradeuser.Activated = reader.GetBoolean(7);
                            tradeuser.UserStatus = (SimTradeUserStatusEnmu)reader.GetInt16(8);
                            tradeuser.DisabledTime = reader.IsDBNull(9) ? DateTime.MinValue : reader.GetDateTime(9);
                            tradeuser.DailyDrawDown = reader.GetDecimal(10);
                            tradeuser.UserPrivilege = reader.GetInt16(11);
                            tradeuser.DrawDownDate = reader.IsDBNull(12) ? DateOnly.MinValue : DateOnly.FromDateTime(reader.GetDateTime(12));

                            // 根据需要更新用户状态
                            if (tradeuser.DisabledTime < DateTime.Now.Date && tradeuser.UserStatus <= SimTradeUserStatusEnmu.ForbidToday)
                            {
                                tradeuser.UserStatus = SimTradeUserStatusEnmu.Normal;
                            }
                        }
                    }
                    connection.Close();
                }
            }
            catch(Exception ex)
            {
                connection?.Close();
            }

            //using (var db = _database.GetReaderContext()) // 假设 _database.GetReaderContext() 返回一个 NpgsqlConnection
            //{
            //    // 使用 NpgsqlConnection 对象 db，而不是全局的 connection 对象

            //}


            return tradeuser;
        }


        //public TradeSimUser GetTradeSimSingleUser(int UserID)
        //{
        //    TradeSimUser tradeuser = new TradeSimUser();
        //    tradeuser.Activated = false;
        //    using (var db = _database.GetReaderContext())
        //    {
        //        string sql = $"select a.id,user_id,max_profit,max_loss,b.allowed_total_loss,b.volume,allowed_daily_loss,activated,user_status,disable_start_date,daily_draw_down,a.user_privilege,draw_down_date from trade_simulation_users as a inner join trade_simulation_config as b on a.user_privilege = b.id where user_id = {UserID}";
        //        using var cmd = new NpgsqlCommand(sql, connection);
        //        using (var reader = cmd.ExecuteReader())
        //        {
        //            if (reader.Read())
        //            {
        //                tradeuser.id = reader.GetInt32(0);
        //                tradeuser.UserID = reader.GetInt32(1);
        //                tradeuser.MaxProfit = reader.GetDecimal(2);
        //                tradeuser.MaxLoss = reader.GetDecimal(3);
        //                tradeuser.AllowedTotalLoss = reader.GetDecimal(4);
        //                tradeuser.TotalAllowedSingleOpen = reader.GetInt32(5);
        //                tradeuser.TotalAllowedMaxOpen = tradeuser.TotalAllowedSingleOpen;
        //                tradeuser.AllowedDailyLoss = reader.GetDecimal(6);
        //                tradeuser.Activated = reader.GetBoolean(7);
        //                tradeuser.UserStatus = (SimTradeUserStatusEnmu)(UserHelper.SimTradeUserStatusEnmu)reader.GetInt16(8);
        //                tradeuser.DisabledTime = reader.IsDBNull("disable_start_date") ? DateTime.MinValue : reader.GetDateTime(9);
        //                tradeuser.DailyDrawDown = reader.GetDecimal(10);
        //                tradeuser.UserPrivilege = reader.GetInt16(11);
        //                tradeuser.DrawDownDate = reader.IsDBNull("draw_down_date") ? DateOnly.MinValue : DateOnly.FromDateTime(reader.GetDateTime(12));
        //                if (tradeuser.DisabledTime < DateTime.Now.Date & tradeuser.UserStatus <= (SimTradeUserStatusEnmu)UserHelper.SimTradeUserStatusEnmu.ForbidToday)
        //                {
        //                    tradeuser.UserStatus = (SimTradeUserStatusEnmu)UserHelper.SimTradeUserStatusEnmu.Normal;
        //                }
        //            }
        //        }
        //        return tradeuser;

        //    }
        //}




        /// <summary>
        /// 获取一个券的最新价格
        /// </summary>
        /// <param name="ts"></param>
        /// <param name="NoForward"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public decimal GetLatestPrice(TSInfoRow ts, bool NoForward = false)
            {
                try
                {
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return 0;
                        }

                        string sql;
                        if (NoForward)
                        {
                            sql = $"SELECT tradeprice from tradehistory_id{ts.PoolId} where tscode = '{ts.tsCode}' and forwardcontact = false and withdraw = false ORDER BY tradedate desc limit 1";
                        }
                        else
                        {
                            sql = $"SELECT tradeprice from tradehistory_id{ts.PoolId} where tscode = '{ts.tsCode}' and withdraw = false ORDER BY tradedate desc limit 1";
                        }

                        using (var command = db.Database.GetDbConnection().CreateCommand())
                        {
                            command.CommandText = sql;
                            db.Database.OpenConnection();

                            using (var reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    return reader.GetDecimal(0);
                                }

                                return 0;
                            }

                        }
                    }

                }
                catch (Exception ex)
                {
                AppLog.WriteError("ex" + ex.Message + "GetLatestPrice");
                    return 0;
                }
            }

        public bool UpdateUserTradeVolumeConfig(UserTradeVolumeConfig config)
        {
            try
            {
                using (var db = _database.GetWriterContext())
                {
                    var existingConfig = db.UserTradeVolumeConfigs.FirstOrDefault(c => c.Tscode == config.Tscode);
                    if (existingConfig != null)
                    {
                        existingConfig.Volume = config.Volume;
                        db.Update(existingConfig);
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "UpdateUserTradeVolumeConfig" + ex.StackTrace);
                return false;
            }
            finally
            {
                _database.CloseWriter();
            }
            return true;
        }
        /// <summary>
        /// 增加个人买量
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddUserTradeVolumeConfig(UserTradeVolumeConfig v)
            {
                try
                {
                    using (var db = _database.GetWriterContext()) // 获取写入连接
                    {
                        v.UserId = UserHelper.UserID;
                        db.UserTradeVolumeConfigs.Add(v);

                        // 保存更改到数据库
                        db.SaveChanges();
                        //using (var cmd = connection.CreateCommand())
                        //{
                        //    cmd.CommandText = sql;
                        //    cmd.ExecuteNonQuery();
                        //}

                    }

                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "AddUserTradeVolumeConfig" + ex.StackTrace);
                    return false;
                }
                finally
                {
                    _database.CloseWriter();
                }
                return true;
            }

        /// <summary>
        /// 移除个人买量
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public bool RemoveUserTradeVolumeConfig(UserTradeVolumeConfig v)
        {
            try
            {
                using (var db = _database.GetWriterContext()) // 获取写入连接
                {
                    db.UserTradeVolumeConfigs.Remove(v);

                    // 保存更改到数据库
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "RemoveUserTradeVolumeConfig" + ex.StackTrace);
                return false;
            }
            finally
            {
                _database.CloseWriter();
            }
            return true;
        }

        /// <summary>
        /// 拿到买量（个人）
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<UserTradeVolumeConfig> GetUserTradeVolumeConfig(int UserID)
            {
                List<UserTradeVolumeConfig> volumes = new List<UserTradeVolumeConfig>();
                try
                {
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return volumes;
                        }
                        volumes = db.UserTradeVolumeConfigs.Where(o => o.UserId == UserID).ToList();
                        return volumes;
                    }
                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "GetUserTradeVolumeConfig" + ex.StackTrace);
                }
                return volumes;
            }


        /// <summary>
        /// 拿到下单历史记录,注意，这是个websocket实现
        /// </summary>
        /// <param name="TsCode"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        public async Task<List<BidHistory>> GetBidHistoriesAsync(string TsCode)
        {
            List<BidHistory> tmpBids = new List<BidHistory>();
            try
            {
                string tmp = "";
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
                    client.Timeout = TimeSpan.FromSeconds(10); // 增加超时时间
                    client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");

                    HttpResponseMessage res = await RetryPolicy.ExecuteAsync(() => client.GetAsync($"{DataHelper.BaseConfig.HttpUrl}/latestbid/realtime?tscode={TsCode}&bidtype=0"));
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        tmp = await res.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        AppLog.WriteError($"HTTP request failed with status code {res.StatusCode}");
                        return tmpBids;
                    }
                }

                JObject o = JObject.Parse(tmp);
                tmpBids = JsonConvert.DeserializeObject<List<BidHistory>>(o["value"].ToString());

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
                    client.Timeout = TimeSpan.FromSeconds(10); // 增加超时时间
                    client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");

                    HttpResponseMessage res = await RetryPolicy.ExecuteAsync(() => client.GetAsync($"{DataHelper.BaseConfig.HttpUrl}/latestbid/realtime?tscode={TsCode}&bidtype=1"));
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        tmp = await res.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        AppLog.WriteError($"HTTP request failed with status code {res.StatusCode}");
                        return tmpBids;
                    }
                }

                o = JObject.Parse(tmp);
                tmpBids.AddRange(JsonConvert.DeserializeObject<List<BidHistory>>(o["value"].ToString()));
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "GetBidHistories" + ex.StackTrace);
            }
            return tmpBids.Where(x => x.Forward == false).ToList();
        }

        public static class RetryPolicy
        {
            public static async Task<T> ExecuteAsync<T>(Func<Task<T>> action, int maxRetryCount = 3, int delayMilliseconds = 2000)
            {
                int retryCount = 0;
                while (true)
                {
                    try
                    {
                        return await action();
                    }
                    catch (Exception ex) when (retryCount < maxRetryCount)
                    {
                        retryCount++;
                        AppLog.WriteError($"Retrying {retryCount}/{maxRetryCount} after exception: {ex.Message}");
                        await Task.Delay(delayMilliseconds);
                    }
                }
            }
        }

        //public async Task<List<BidHistory>> GetBidHistoriesAsync(string TsCode)
        //{
        //    List<BidHistory> tmpBids = new List<BidHistory>();
        //    try
        //    {
        //        string tmp = "";
        //        using (var client = new HttpClient())
        //        {
        //            client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
        //            client.Timeout = TimeSpan.FromSeconds(3);
        //            client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");

        //            HttpResponseMessage res = await client.GetAsync($"{DataHelper.BaseConfig.HttpUrl}/latestbid/realtime?tscode={TsCode}&bidtype=0");
        //            if (res.StatusCode == HttpStatusCode.OK)
        //            {
        //                tmp = await res.Content.ReadAsStringAsync();
        //            }
        //        }

        //        JObject o = JObject.Parse(tmp);
        //        tmpBids = JsonConvert.DeserializeObject<List<BidHistory>>(o["value"].ToString());

        //        using (var client = new HttpClient())
        //        {
        //            client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
        //            client.Timeout = TimeSpan.FromSeconds(3);
        //            client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");

        //            HttpResponseMessage res = await client.GetAsync($"{DataHelper.BaseConfig.HttpUrl}/latestbid/realtime?tscode={TsCode}&bidtype=1");
        //            if (res.StatusCode == HttpStatusCode.OK)
        //            {
        //                tmp = await res.Content.ReadAsStringAsync();
        //            }
        //        }

        //        o = JObject.Parse(tmp);
        //        tmpBids.AddRange(JsonConvert.DeserializeObject<List<BidHistory>>(o["value"].ToString()));
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError(ex.Message + "DailyData" + "GetBidHistories" + ex.StackTrace);
        //    }
        //    return tmpBids.Where(x => x.Forward == false).ToList();
        //}

        //public List<BidHistory> GetBidHistories(string TsCode)
        //{
        //    List<BidHistory> tmpBids = new List<BidHistory>();
        //    try
        //    {
        //        string tmp = "";
        //        using (var client = new HttpClient())
        //        {
        //            client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
        //            client.Timeout = new TimeSpan(0, 0, 3);
        //            client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");
        //            HttpResponseMessage res = client.GetAsync(string.Format($"{DataHelper.BaseConfig.HttpUrl}/latestbid/realtime?tscode={TsCode}&bidtype=0")).Result;
        //            if (res.StatusCode == HttpStatusCode.OK)
        //            {
        //                tmp = res.Content.ReadAsStringAsync().Result;
        //            }
        //        }
        //        JObject o = JObject.Parse(tmp);
        //        tmpBids = JsonConvert.DeserializeObject<List<BidHistory>>(o["value"].ToString());

        //        using (var client = new HttpClient())
        //        {
        //            client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
        //            client.Timeout = new TimeSpan(0, 0, 3);
        //            client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");
        //            HttpResponseMessage res = client.GetAsync(string.Format($"{DataHelper.BaseConfig.HttpUrl}/latestbid/realtime?tscode={TsCode}&bidtype=1")).Result;
        //            if (res.StatusCode == HttpStatusCode.OK)
        //            {
        //                tmp = res.Content.ReadAsStringAsync().Result;
        //            }
        //        }
        //        o = JObject.Parse(tmp);
        //        tmpBids.AddRange(JsonConvert.DeserializeObject<List<BidHistory>>(o["value"].ToString()));
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError(ex.Message + "DailyData" + "GetBidHistories" + ex.StackTrace);
        //    }
        //    return tmpBids.Where(x => x.Forward == false).ToList();
        //}


        /// <summary>
        /// 拿到最近的成交价
        /// </summary>
        /// <param name="ts"></param>
        /// <param name="NoForward"></param>
        /// <param name="dtStart"></param>
        /// <returns></returns>
        public decimal GetLastClosePrice(TSInfoRow ts, bool NoForward = false, DateTime? dtStart = null)
            {
                try
                {
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return 0;
                        }

                        string sql;
                        if (NoForward)
                        {
                            if (dtStart == null)
                            {
                                sql = $"SELECT tradeprice from tradehistory_id{ts.PoolId} where tscode = '{ts.tsCode}' and forwardcontact = false and withdraw = false ORDER BY tradedate desc limit 1";
                            }
                            else
                            {
                                sql = $"SELECT tradeprice from tradehistory_id{ts.PoolId} where tscode = '{ts.tsCode}' and forwardcontact = false and tradedate<='{dtStart:yyyy-MM-dd HH:mm:ss}' and withdraw = false ORDER BY tradedate desc limit 1";
                            }
                        }
                        else
                        {
                            if (dtStart == null)
                            {
                                sql = $"SELECT tradeprice from tradehistory_id{ts.PoolId} where tscode = '{ts.tsCode}' and withdraw = false ORDER BY tradedate desc limit 1";
                            }
                            else
                            {
                                sql = $"SELECT tradeprice from tradehistory_id{ts.PoolId} where tscode = '{ts.tsCode}' and tradedate<='{dtStart:yyyy-MM-dd HH:mm:ss}' and withdraw = false ORDER BY tradedate desc limit 1";
                            }
                        }
                        using (var command = db.Database.GetDbConnection().CreateCommand())
                        {
                            command.CommandText = sql;
                            db.Database.OpenConnection();

                            using (var reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    return reader.GetDecimal(0);
                                }

                                return 0;
                            }

                        }
                    }
                }

                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "GetLastClosePrice" + ex.StackTrace);
                }
                return 0;
            }


            public List<TradeHistoryRow> GetTradeHistoryByDate(TSInfoRow ts, DateOnly dStart, DateOnly dEnd, bool NoForward = false)
            {
                try
                {
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return null; // 返回一个空列表
                        }
                        if (ts == null)
                        {
                            return new List<TradeHistoryRow>();
                        }

                        int poolId = ts.PoolId;
                        List<TradeHistoryRow> tradeHistoryRows = new List<TradeHistoryRow>();
                        var tableName = $"tradehistory_id{poolId}";

                        var tempBrokers = GetBroker();
                        string sql = $"SELECT tscode, tradeprice, dealtype, tradetime, tradedate, brokerid, forwardcontact, tradeid, id, netprice, withdraw, settle_speed FROM tradehistory_id{poolId} WHERE tscode='{ts.tsCode}' AND tradedate>='{dStart:yyyy-MM-dd}' AND tradedate<'{dEnd.AddDays(1):yyyy-MM-dd}'";

                        if (NoForward)
                        {
                            sql += " AND forwardcontact = false";
                        }

                        sql += " ORDER BY tradedate";

                        using (var command = db.Database.GetDbConnection().CreateCommand())
                        {
                            command.CommandText = sql;
                            db.Database.OpenConnection();

                            using (var reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var tradeHistoryRow = new TradeHistoryRow
                                    {
                                        TsCode = reader["TsCode"].ToString(),
                                        TradePrice = Convert.ToDecimal(reader["TradePrice"]),
                                        DealType = reader["DealType"].ToString(),
                                        TradeTime = reader["TradeTime"].ToString(),
                                        TradeDate = Convert.ToDateTime(reader["TradeDate"]),
                                        BrokerID = Convert.ToInt32(reader["BrokerID"]),
                                        BrokerName = tempBrokers[Convert.ToInt32(reader["BrokerID"])],
                                        Forward = Convert.ToBoolean(reader["ForwardContact"]),
                                        Date = DateOnly.FromDateTime(Convert.ToDateTime(reader["TradeDate"])),
                                        TradeID = reader["TradeID"] == DBNull.Value ? "" : reader["TradeID"].ToString(),
                                        id = Convert.ToInt32(reader["id"]),
                                        NetPrice = Convert.ToDecimal(reader["NetPrice"]),
                                        Withdraw = Convert.ToBoolean(reader["Withdraw"]),
                                        SettleSpeed = reader["Settle_Speed"].ToString()
                                    };
                                    tradeHistoryRows.Add(tradeHistoryRow);
                                }

                                return tradeHistoryRows;
                            }

                        }


                    }

                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "GetTradeHistoryByDate" + ex.StackTrace);
                }
                return null;
            }

            /// <summary>
            /// 拿到所有中介
            /// </summary>
            /// <returns></returns>
            public List<string> GetBroker()
            {
                try
                {
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return null; // 返回一个空列表
                        }
                        List<string> brokers = new List<string>();
                        brokers = db.Brokers.OrderBy(u => u.Id).Select(o => o.Broker1).ToList();
                        return brokers;
                    }

                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "GetTradeHistoryByDate" + ex.StackTrace);
                }
                return null;
            }
            public List<string> GetAllTsCodes(bool Valid)
            {
                List<string> TsCodes = new List<string>();

                try
                {
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return TsCodes; // 返回一个空列表
                        }

                        IQueryable<Tsinfo> query;
                        var today = DateOnly.FromDateTime(DateTime.Now);
                        if (Valid)
                        {
                            query = db.Tsinfos
                                      .Where(ts => ts.Maturitydate >= today)
                                      .OrderByDescending(ts => ts.Tscode);
                        }
                        else
                        {
                            query = db.Tsinfos
                                      .OrderByDescending(ts => ts.Tscode);
                        }

                        TsCodes = query
                                  .Where(ts => !ts.Tscode.Contains("CTD"))
                                  .Select(ts => ts.Tscode)
                                  .ToList();
                    }

                }
                catch (Exception ex)
                {
                    // 处理异常
                    AppLog.WriteError(ex.Message + "DailyData" + "GetAllTsCodes" + ex.StackTrace);
                }

                return TsCodes;
            }

            /// <summary>
            /// 根据券码获得具体TSInfo
            /// </summary>
            /// <param name="BondCode"></param>
            /// <returns></returns>
            public TSInfoRow GetBondByCode(string BondCode)
            {
                try
                {
                    using (var db = _database.GetReaderContext())
                    {

                        if (!db.IsDbConnectionOpen())
                        {
                            return null; // 返回一个空列表
                        }
                        TSInfoRow tsInfo = db.Tsinfos
        .Where(ts => ts.Tscode == BondCode)
        .Select(ts => new TSInfoRow
        {
            id = ts.Id,
            tsCode = ts.Tscode,
            StartDate = ts.Startdate,
            BondKey = ts.Bondkey,
            LastDayCrawled = ts.Lastdaycrawled.HasValue ? ts.Lastdaycrawled.Value : null,
            BondName = ts.Bondname,
            ListedMarket = ts.Listedmarket,
            BondRating = ts.Bondrating,
            IssueRate = ts.Issuerate,
            IssueAmount = ts.Issueamount,
            IssuePrice = ts.Issueprice,
            Maturity = ts.Maturity,
            MaturityDate = ts.Maturitydate.HasValue ? ts.Maturitydate.Value : null,
            BondFullName = ts.Bondfullname,
            RealTime = ts.Realtime.HasValue ? ts.Realtime.Value : false,

            InterestPerYear = (int)ts.Interestperyear,
            FirstTradeDate = ts.Firsttradedate.HasValue ? ts.Firsttradedate.Value : DateOnly.MinValue,
            InterestDate = ts.Intereststartdate.HasValue ? ts.Intereststartdate.Value : DateOnly.MinValue,
            QBDate = ts.Qbdate,
            LastdayCrawledTime = ts.Lastdaycrawledtime.HasValue ? ts.Lastdaycrawledtime.Value : DateTime.MinValue,

            PoolId = (int)ts.Poolid,
            PVBP = (decimal)ts.Basicvalue,
            HengShengMarketID = ts.HengshengId,
            HengShengMarketName = ts.HengshengName
        })
        .FirstOrDefault(); // 或者 SingleOrDefault()
                        return tsInfo;


                    }

                }
                catch (Exception ex)
                {
                    // 处理异常
                    AppLog.WriteError(ex.Message + "DailyData" + "GetBondByCode" + ex.StackTrace);
                }
                return null;
            }



        /// <summary>
        /// 获取所有券码信息
        /// </summary>
        /// <returns></returns>
        public  List<Tsinfo> GetAllTsInfos()
        {
            try
            {
                using (var db = _database.GetReaderContext())
                {

                    if (!db.IsDbConnectionOpen())
                    {
                        return null; // 返回一个空列表
                    }
                    return db.Tsinfos.ToList();

                }

            }
            catch (Exception ex)
            {
                // 处理异常
                AppLog.WriteError(ex.Message + "DailyData" + "GetAllTsInfos" + ex.StackTrace);
            }
            return null;
        }
        #endregion

        #region 服务端接口实现

        /// <summary>
        /// 目前不知道咋返回通道id，就返回第一个
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public string GetChannelId()
        {
           
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return string.Empty; // 返回一个空列表
                    }
                    return db.Channels.ToList()[0].Id;
                 
                }

            }
            catch (Exception ex)
            {
                // 处理异常
                AppLog.WriteError(ex.Message + "DailyData" + "GetChannelId" + ex.StackTrace);
            }

            return null;
        }

        /// <summary>
        /// 添加至chatmessage表
        /// </summary>
        /// <param name="brokerId"></param>
        /// <param name="newChatMessages"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void AddChatMessageList(int brokerId, List<ChatMessage> newChatMessages)
        {
            try
            {
                using (var db = _database.GetWriterContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return;
                    }
                    string channelId = DailyData.ChannelId;
                    if (newChatMessages.Any())
                    {
                        DateTime updateTime = DateTime.Now;

                        foreach (var message in newChatMessages)
                        {
                            message.BrokerId = brokerId;
                            message.UpdateTime = updateTime; // 设置创建时间
                            message.Id = Guid.NewGuid().ToString(); // 使用Guid.NewGuid()生成UUID
                            message.ChannelId = channelId;
                        }

                        db.ChatMessages.AddRange(newChatMessages); // 将新消息添加到数据库中
                        db.SaveChanges(); // 保存更改
                    }

                    AppLog.WriteInfo("DailyData" + "中介号：" + brokerId + "——AddChatMessageList增加" + newChatMessages.Count + "条消息内容");
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("DailyData" + "AddChatMessageList添加消息异常：" + ex.Message);
            }
            finally
            {
                _database.CloseWriter(); // 关闭数据库连接
            }
        }



        public void DelChatMessageList(int brokerId, DateTime dateStartTime, DateTime? dateEndTime = null)
        {
            try
            {
                using (var db = _database.GetWriterContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return;
                    }

                    IQueryable<ChatMessage> query = db.ChatMessages.Where(cm => cm.BrokerId == brokerId);
                    List<ChatMessage> temp = query.ToList();
                    if (dateEndTime.HasValue)
                    {
                        query = query.Where(cm => cm.UpdateTime >= dateStartTime && cm.UpdateTime <= dateEndTime);
                    }
                    else
                    {
                        dateEndTime = dateStartTime.Date.AddDays(1); // 如果只传入了 dateStartTime，则删除当天的数据
                        query = query.Where(cm => cm.UpdateTime >= dateStartTime.Date && cm.UpdateTime < dateEndTime);
                    }

                    List<ChatMessage> delChatMessages = query.ToList();
                    db.ChatMessages.RemoveRange(delChatMessages);
                    db.SaveChanges();

                    AppLog.WriteInfo($"DailyData 根据UpdateTime删除聊天数据：中介号 {brokerId}，删除了 {delChatMessages.Count} 条消息内容");
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"DailyData DelChatMessageList删除消息异常：{ex.Message}");
            }
            finally
            {
                _database.CloseWriter(); // 关闭数据库连接
            }
        }



        /// <summary>
        /// 删除实际聊天记录的时间
        /// </summary>
        /// <param name="brokerId"></param>
        /// <param name="dateStartTime"></param>
        /// <param name="dateEndTime"></param>
        public void DelChatMessageListByCreateTime(int brokerId, DateTime? dateStartTime = null, DateTime? dateEndTime = null)
        {
            try
            {
                using (var db = _database.GetWriterContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return;
                    }

                    IQueryable<ChatMessage> query = db.ChatMessages.Where(cm => cm.BrokerId == brokerId);

                    if (dateStartTime.HasValue)
                    {
                        query = query.Where(cm => cm.CreateTime >= dateStartTime.Value);
                    }

                    if (dateEndTime.HasValue)
                    {
                        query = query.Where(cm => cm.CreateTime <= dateEndTime.Value);
                    }

                    List<ChatMessage> delChatMessages = query.ToList();
                    db.ChatMessages.RemoveRange(delChatMessages);
                    db.SaveChanges();

                    AppLog.WriteInfo($"DailyData 根据CreateTime删除聊天数据：中介号 {brokerId}，删除了 {delChatMessages.Count} 条消息内容");
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"DailyData DelChatMessageListByCreateTime：{ex.Message}");
            }
            finally
            {
                _database.CloseWriter(); // 关闭数据库连接
            }
        }




        /// <summary>
        /// 根据中介名查找默认条数的聊天记录
        /// </summary>
        /// <param name="brokerName"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<ChatMessage> GetRecentMessagesByBrokerName(int brokerId, int number = 0)
        {
            List<ChatMessage> chatMessages = new List<ChatMessage>();

            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return chatMessages; // 返回一个空列表
                    }
                    //0返回所有数据
                    if(number==0)
                    {
                        chatMessages = db.ChatMessages.Where(o => o.BrokerId == brokerId).OrderByDescending(a => a.CreateTime).ToList();
                    }
                    else
                    {
                        chatMessages = db.ChatMessages.Where(o => o.BrokerId == brokerId).OrderByDescending(a => a.CreateTime).Take(number).ToList();
                    }
                    
                    return chatMessages;
                   
                }

            }
            catch (Exception ex)
            {
                // 处理异常
                AppLog.WriteError(ex.Message + "DailyData" + "GetRecentMessagesByBrokerName" + ex.StackTrace);
            }

            return chatMessages;
        }


        /// <summary>
        /// 插入一条复议记录
        /// </summary>
        /// <param name="qSR"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddRequestReview(QuanYiOrderServerResponseClass qSR)
        {
            try
            {
                using (var db = _database.GetWriterContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return false;
                    }
                    var existingTrade = db.ReviewMessages.FirstOrDefault(t => t.UserTradeId == qSR.Trade.UserTradeID);
                    //插入一条
                    db.ReviewMessages.Add(new ReviewMessage()
                    {
                        CreateTime = DateTime.Now,
                        ReviewMessageInfo = qSR.RequestReviewMessage,
                        Status = 0,
                        UserTradeId = (int?)qSR.Trade.UserTradeID,
                        UserId = qSR.Trade.UserID
                    });
                    db.SaveChanges(); // 保存更改


                    var temp2 = db.UserTradeBondhelpers;
                    AppLog.WriteInfo("DailyData" + "AddRequestReview增加一条新的复议" + qSR.Trade.ToString()+"复议内容"+qSR.RequestReviewMessage);
                    return true; // 更新成功
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("DailyData" + "AddRequestReview增加一条新的复议异常" + qSR.Trade.ToString()+"复议内容"+qSR.RequestReviewMessage+ex.Message);
                
                return false; // 更新过程中发生异常，更新失败
            }
            finally
            {
                _database.CloseWriter(); // 关闭数据库连接
            }
        }



        /// <summary>
        /// 改价实现
        /// </summary>
        /// <param name="trade"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateUserTrade(UserTrade trade)
        {
            try
            {
                using (var db = _database.GetWriterContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return false;
                    }
                    var existingTrade = db.UserTradeBondhelpers.FirstOrDefault(t => t.UserTradeId == trade.UserTradeID);
                    if (existingTrade == null)
                    {
                        return false; // 如果找不到对应的记录，更新失败
                    }
                    var temp = db.UserTradeBondhelpers;
                    // 更新现有记录的价格
                    existingTrade.Price = trade.Price;
                    existingTrade.Deliverydate = trade.DeliveryDate;
                    existingTrade.Volume = trade.Volume;
                    db.UserTradeBondhelpers.Update(existingTrade);
                    db.SaveChanges(); // 保存更改


                    var temp2 = db.UserTradeBondhelpers.ToList() ;
                    AppLog.WriteInfo( "DailyData" + "UpdateUserTrade更新usertrade成功"+trade.ToString());
                    return true; // 更新成功
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "TradeSimLog+QuanYiOrderServerResponseClass" + ex.StackTrace);
                return false; // 更新过程中发生异常，更新失败
            }
            finally
            {
                _database.CloseWriter(); // 关闭数据库连接
            }
        }





        public void TradeSimLog(QuanYiServerResponseClass qsr)
            {
                try
                {
                    using (var db = _database.GetWriterContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return;
                        }
                        var logEntry = new TradeSimulationLog
                        {
                            UserId = qsr.UserID,
                            LogDate = DateTime.Now,
                            Action = qsr.DataType.ToString(),
                            LogData = JsonConvert.SerializeObject(qsr.QCT),
                            RemoteIp = qsr.RemoteIP,
                            Message = qsr.Message
                        };

                        db.TradeSimulationLogs.Add(logEntry);
                        db.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "TradeSimLog+QuanYiServerResponseClass" + ex.StackTrace);
                }
                finally
                {
                    _database.CloseWriter();
                }
                return;
            }

            public void TradeSimLog(QuanYiOrderServerResponseClass qsr)
            {
                try
                {
                    using (var db = _database.GetWriterContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return;
                        }
                        var logEntry = new TradeSimulationLog
                        {
                            UserId = qsr.UserID,
                            LogDate = DateTime.Now,
                            Action = qsr.DataType.ToString(),
                            LogData = JsonConvert.SerializeObject(qsr.Trade),
                            RemoteIp = qsr.RemoteIP,
                            Message = qsr.Message
                        };

                        db.TradeSimulationLogs.Add(logEntry);
                        db.SaveChanges();


                    }
                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "TradeSimLog+QuanYiOrderServerResponseClass" + ex.StackTrace);
                }
                finally
                {
                    _database.CloseWriter();
                }
                return;
            }



            public bool AddUserTrade(UserTrade trade, out string msg)
            {
                try
                {
                    using (var db = _database.GetWriterContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            msg = "Database connection is not open.";
                            return false;
                        }

                        var userTradeBondHelper = new UserTradeBondhelper
                        {
                            Tscode = trade.TsCode,
                            UserTradeId = trade.UserTradeID,
                            Price = trade.Price,
                            Volume = trade.Volume,
                            Broker = trade.Broker,
                            BrokerId = (short?)trade.BrokerID,
                            Chatid = trade.ChatID,
                            Userid = trade.UserID,
                            Deliverydate = trade.DeliveryDate,
                            Time = trade.Time,
                            Dealtype = trade.DealType,
                            ReceiverId = trade.ReceiverId,
                            Command = trade.Command,
                            OrderType = (short?)trade.OrderType,
                            Guid = trade.Guid,
                            DailyId = (short?)trade.DailyID,
                            RestVolume = trade.OnHoldVolume.ToString()
                        };

                        db.UserTradeBondhelpers.Add(userTradeBondHelper);
                        db.SaveChanges();
                        AppLog.WriteInfo("DailyData" + "AddUserTrade增加用户交易成功");
                        msg = "Add UserTrade Successfully";
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "AddUserTrade增加用户交易" + ex.StackTrace);
                    msg = "An error occurred while adding UserTrade.";
                    return false;
                }
            finally
            {
                _database.CloseWriter();
            }
            }



        #endregion

        #region 通用接口实现

        public List<string> GetAllTsTypes()
        {


            try
            {
                List<string> tsTypes = new List<string>();
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return tsTypes;
                    }

                  
                    return db.Tstypes.Distinct().Select(o=>o.Tstype1).ToList();
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "DailyData" + "Holidays" + ex.StackTrace);
            }
            return null;
        }

        public static async Task<List<DateOnly>> GetHolidaysAsync()
        {
            string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/holidays/getAll";

            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 GET 请求并获取响应内容
                    string responseContent = await client.GetStringAsync(apiUrl);

                    // 使用 JObject 解析 JSON 数据
                    var json = JObject.Parse(responseContent);

                    // 提取 code 和 value 字段
                    var code = json["code"]?.ToString();
                    var value = json["value"]?.ToObject<List<DateOnly>>();

                    // 检查 code 是否为 "00000" 并返回 value
                    if (code == "00000")
                    {
                        return value ?? new List<DateOnly>();
                    }
                    else
                    {
                        // 可以记录日志或其他处理
                        return new List<DateOnly>();
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"{ex.Message} DailyData Holidays {ex.StackTrace}");
                return new List<DateOnly>(); // 处理异常情况并返回空列表
            }
        }

        //public static List<DateOnly> Holidays()
        //    {

        //    try
        //    {
        //        string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/holidays/getAll";
        //        using (var client = new HttpClient())
        //        {
        //            client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

        //            // 发送 GET 请求并获取响应内容
        //            string responseContent = client.GetStringAsync(apiUrl).Result;

        //            // 使用 JObject 解析 JSON 数据
        //            var json = JObject.Parse(responseContent);

        //            // 提取 code 和 value 字段
        //            var code = json["code"]?.ToString();
        //            var value = json["value"]?.ToObject<List<DateOnly>>();

        //            // 检查 code 是否为 "00000" 并返回 value
        //            if (code == "00000")
        //            {
        //                return value ?? new List<DateOnly>();
        //            }
        //            else
        //            {
        //                return new List<DateOnly>(); // 或者返回 null，根据需求选择
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError(ex.Message + "DailyData" + "Holidays" + ex.StackTrace);
        //        return new List<DateOnly>(); // 处理异常情况并返回空列表
        //    }
        //}


        public List<Setting> GetConfigs(string parameter)
            {
                List<Setting> configs = new List<Setting>();
                try
                {
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return configs;
                        }
                        configs = db.Settings.Where(o => o.Parameter == parameter).ToList();
                        return configs;
                    }
                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "GetConfigs" + ex.StackTrace);
                }
                return configs;
            }
            #endregion

            #region 恒生相关
            public List<HengShengMarketInfo> GetHengShengMarketInfo()
            {
                try
                {
                    List<HengShengMarketInfo> hengShengMarketInfos = new List<HengShengMarketInfo>();
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return hengShengMarketInfos;
                        }


                        hengShengMarketInfos = db.HengshengMarkets
                           .Where(m => (bool)!m.Deleted) // 查询未被删除的记录
                           .Select(m => new HengShengMarketInfo
                           {
                               id = m.Id,
                               MarketName = m.MarketName,
                               FileName = m.FileName
                           })
                           .ToList();
                        return hengShengMarketInfos;
                    }
                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "GetHengShengMarketInfo" + ex.StackTrace);
                }
                return new List<HengShengMarketInfo>();
            }

            public List<TSInfoRow> GetTSInfoForHengSheng()
            {
                try
                {
                    List<TSInfoRow> tsInfoRows = new List<TSInfoRow>();
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return tsInfoRows;
                        }


                        tsInfoRows = db.Tsinfos
               .Where(t => (bool)!t.Deleted && t.Firsttradedate <= DateOnly.FromDateTime(DateTime.Today) && !string.IsNullOrEmpty(t.HengshengId))
               .OrderByDescending(t => t.Tscode)
               .Select(t => new TSInfoRow
               {
                   id = t.Id,
                   tsCode = t.Tscode,
                   StartDate = t.Startdate,
                   BondKey = t.Bondkey,
                   LastDayCrawled = t.Lastdaycrawled.HasValue ? t.Lastdaycrawled.Value : null,
                   BondName = t.Bondname,
                   ListedMarket = t.Listedmarket,
                   BondRating = t.Bondrating,
                   IssueRate = t.Issuerate,
                   IssueAmount = t.Issueamount,
                   IssuePrice = t.Issueprice,
                   Maturity = t.Maturity,
                   MaturityDate = t.Maturitydate,
                   BondFullName = t.Bondfullname,
                   RealTime = (bool)t.Realtime,
                   InterestPerYear = (int)t.Interestperyear,
                   FirstTradeDate = t.Firsttradedate.HasValue ? t.Firsttradedate.Value : DateOnly.MinValue,
                   InterestDate = t.Intereststartdate.HasValue ? t.Intereststartdate.Value : DateOnly.MinValue,
                   QBDate = t.Qbdate.HasValue ? t.Qbdate.Value : DateOnly.FromDateTime(DateTime.Now),
                   LastdayCrawledTime = t.Lastdaycrawledtime ?? DateTime.MinValue,
                   PoolId = (int)t.Poolid,
                   HengShengMarketID = t.HengshengId,
                   HengShengMarketName = t.HengshengName,
                   PVBP = (decimal)t.Basicvalue
               })
               .ToList();
                        return tsInfoRows;
                    }
                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "GetTSInfoForHengSheng" + ex.StackTrace);
                }
                return new List<TSInfoRow>();
            }



            #endregion

            #region lily相关
            public int GetLilyTradeLimit(int UserID)
            {
                int MaxVolume = 0;
                try
                {
                    using (var db = _database.GetReaderContext())
                    {
                        if (!db.IsDbConnectionOpen())
                        {
                            return 0;
                        }
                    //MaxVolume = db.SysTradeAmountLimits
                    //    .Where(o => o.UserId == UserID)
                    //    .Select(o => o.)
                    //    .FirstOrDefault();
                    return MaxVolume;
                    }
                }
                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "DailyData" + "GetLilyTradeLimit" + ex.StackTrace);
                }
                return 0;
            }


        #endregion

    }
}
